/* 
 * File:   Game.cpp
 * Author: noe
 * 
 * Created on 5 octobre 2013, 19:35
 */

#include "Game.h";
#include "NetworkManager.h"


static Game* game;

Game::Game(int width, int height) {
    this->width = width;
    this->height = height;
    this->running = false;
    this->currentState = 0;
	
	SDL_Init(SDL_INIT_VIDEO);
	SDL_WM_SetCaption("Defensia",NULL);
	SDL_SetVideoMode(width, height, 32, SDL_OPENGL);
	
	glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective(70,(double)width/height,1,1000);
    glEnable(GL_DEPTH_TEST);
}

Game::Game(const Game& orig) {
}

Game::~Game() {
}

Game* Game::createGame(int width, int height)
{
	if(game != NULL)
	{
		std::cerr << "the game has already been created";
		return NULL;
	}
	else
	{
		game = new Game(width, height);
		return game;
	}
	
}
Game* Game::getGame()
{
	if(game == NULL)
	{
		std::cerr << "you must create the game first";	
	}
	else
	{
		return game;
	}
}

State* Game::getCurrentState() const {
    return currentState;
}

int Game::getHeight() const
{
    return height;
}


int Game::getWidth() const
{
    return width;
}


void Game::setCurrentState(State* state)
{
	free(this->currentState);
    this->currentState = state;
}

NetworkManager* Game::getNetworkManager()
{
	return this->nm;
}


bool Game::start()
{
    if(this->running == false)
    {
		if (this->currentState != 0)
		{
//			glEnable(GL_DEPTH_TEST);
//			glEnable(GL_TEXTURE_2D);
//			glClearColor(1,1,1,1);
			
			this->nm = new NetworkManager();
			
			if(this->nm->connectTo("127.0.0.1"))
			{
				std::cout << "connected to server! \n";
			}
			else
			{
				std::cout << "could not connect to server\n";
			}
			
			this->running = true;
			std::cout << "running...\n";

			while(this->running)
			{
				mainloop();
			}		
			SDL_Quit();
		
		}
		else
		{
			std::cerr << "the state cannot be null\n";
			return false;
		}
        
    }
    else
    {	
		std::cerr << "the game is already running\n";
        return false;
    }
}


void Game::stop()
{
    this->running = false;
	std::cout << "stopping...";
}

bool Game::isRunning() const
{

	return this->running;
}

void Game::mainloop()
{
	int loopBegin = 0;
	int loopEnd = 0;
	int delta;
	
	this->frameRate = 1000/60;
	
	while(this->running)
	{
		loopBegin = SDL_GetTicks();
						
		if(isExitRequested())
		{
			Game::getGame()->stop();
		}
		
		this->currentState->update((float)(delta / 1000));       
		this->currentState->render((float)(delta / 1000));
		
		loopEnd = SDL_GetTicks();
		delta = loopEnd - loopBegin; 
		
		if(delta < frameRate)
			SDL_Delay(frameRate - delta);
		
		
	}
}